
import OnFire from './OnFire';
import { EventName } from './EventName';
import API from './API';

// 官方文档：https://gamedoc.quickapp.cn/

const ErrHandle = {
    1000: '后端接口调用失败',
    1001: '参数错误',
    1002: '广告单元无效',
    1003: '内部错误',
    1004: '无合适的广告',
    1005: '广告组件审核中',
    1006: '广告组件被驳回',
    1007: '广告组件被封禁',
    1008: '广告单元已关闭',
    2001: '小程序启动一定时间内不允许展示插屏广告',
    2002: '距离小程序插屏广告或者激励视频广告上次播放时间间隔不足，不允许展示插屏广告',
    2003: '当前正在播放激励视频广告或者插屏广告，不允许再次展示插屏广告',
    2004: '该项错误不是开发者的异常情况，或因小程序页面切换导致广告渲染失败',
    2005: '插屏广告实例不允许跨页面调用'
}

// 负责魅族API
export default class MZApi {
    private _TAG: any = "MZApi";
    private _versions: string = "v1.0";

    private _bannerID = 'P5YO3p5l';
    private _videoID = '0Pa6okWx';
    private _insertID = 'Rk9LmZIp';

    private _bannerAd = null;
    private _videoAd = null;
    private _interstitialAd = null;

    // 单例模式
    private static _instance: MZApi = null;
    public static getInstance() {
        if (this._instance == null) {
            this._instance = new MZApi();
        }
        return this._instance;
    }

    // 初始化
    init() {
        // 切换到前台
        mz.onShow((res) => { });

        // 游戏异常
        qg.onError((res) => { });

        // 切换到后台
        mz.onHide((res) => { });
    }

    // 登录
    login() {
        return new Promise<any>((resolve, reject) => {
            printLog('MZ登录');
            mz.getIMEI({
                success: (res) => {
                    printLog('获取设备码');
                    const imeiCode = res.imei;
                    API.getInstance().login({ code: imeiCode, type: 1 }).then(_res => {
                        printLog('获取后端返回的用户信息：', _res);
                        if (_res.status) {
                            resolve({
                                status: true,
                                data: _res.data
                            })
                        } else {
                            resolve({
                                status: false,
                                data: _res.data
                            })
                        }
                    })
                },
                fail: (err) => {
                    resolve({
                        status: false,
                        data: '登录异常: ' + err
                    })
                }
            });
        })
    }

    // banner广告
    createBannerAd() {
        const { windowWidth, windowHeight } = qg.getSystemInfoSync();

        // 创建banner实例
        if (this._bannerAd == null) {
            this._bannerAd = qg.createBannerAd({
                adUnitId: this._bannerID,
                left: 0,
                top: 0,
                width: qg.getSystemInfoSync().screenWidth,
                height: 90
            });
        }
        else {
            this._bannerAd.show()
            return;
        }

        // banner显示
        this._bannerAd.show()
        this._bannerAd.onLoad(() => {
            this._bannerAd
                .show()
                .then(() => {
                    console.log("广告显示成功");
                })
                .catch(err => {
                    console.log("广告组件出现问题", err);
                });
        });

        this._bannerAd.onResize(size => {
            this._bannerAd.style.top = windowHeight - size.height;
            this._bannerAd.style.left = (windowWidth - size.width) / 2;
        });

        this._bannerAd.onError(err => {
            this._bannerAd.destroy();
            this._bannerAd = null
        });
    }

    // 销毁广告：Constants.SdkFactory.destroyBarAd();
    hideBarAd() {
        if (this._bannerAd != null) {
            this._bannerAd.destroy();
        }
    }

    // 激励视频
    initVideoAd() {
        this._videoAd = qg.createRewardedVideoAd({
            adUnitId: this._videoID
        });

        // 视频加载完成
        this._videoAd.onLoad(() => {
            console.log('激励视频 广告加载成功');
        });

        this._videoAd.load();

        // 捕获视频流异常事件
        this._videoAd.onError(err => {
            console.log('视频流异常::', ErrHandle[err.errCode]);
            OnFire.getInstance().emit(EventName.ADD_MESSAGE, {
                key: 'TipsMessage',
                value: { path: 'true', text: '无适合的视频广告' }
            });
        });

        // 捕获视频关闭事件
        this._videoAd.onClose((res) => {
            if (res && res.isEnded || res === undefined) {
                // 正常播放结束，可以下发游戏奖励
                console.log('正常关闭视频广告');
                OnFire.getInstance().emit(EventName.PLAY_VIDEO_STATUS, { key: true });
            }
            else {
                // 播放中途退出，不下发游戏奖励
                console.log('还没有看完视频，关闭不正常');
                OnFire.getInstance().emit(EventName.PLAY_VIDEO_STATUS, { key: false });
            }
            //重新创建一次广告
            this.initVideoAd();
        });
    }

    // 播放视频
    playVideoAd() {
        return new Promise<any>((resolve, reject) => {
            if (this._videoAd != null) {
                // this._videoAd.load().then(() => this._videoAd.show().catch(err => {
                //     this._videoAd.load().then(() => {
                //         return this._videoAd.show();
                //     });
                // }));

                // 监听视频播放状态
                OnFire.getInstance().once(EventName.PLAY_VIDEO_STATUS, res => {
                    if (res.key === true) {
                        resolve({
                            status: true,
                            msg: '播放完成'
                        });
                    } else {
                        resolve({
                            status: false,
                            msg: res
                        });
                    };
                })
                this._videoAd.show()
            } else {
                this.initVideoAd();
            }
        })
    }

    // 系统信息(同步)
    getSystemInfoSync() {

    }

    // 长震动
    vibrateLong() {
        mz.vibrateLong({
            success: () => { },
            fail: () => { }
        });
    }

    // 短震动
    vibrateShort() {
        mz.vibrateShort({
            success: () => { },
            fail: () => { }
        });
    }

    //开始录屏
    StartRecordScreen() {
        return;
    }

    // 停止录屏
    StopRecordScreen() {
        return;
    }

    // 分享录屏
    ShareRecordScreen() {
        return new Promise<any>((resolve, reject) => {
            resolve(true);
        });
    }

    // 插屏广告
    interstitialAd(callback) {
        this._interstitialAd = qg.createInterstitialAd({
            adUnitId: this._insertID
        });

        this._interstitialAd.load();

        this._interstitialAd.onLoad(() => {
            printLog('插屏广告加载完成');
            this._interstitialAd.show();
        })

        this._interstitialAd.onClose(() => {
            this._interstitialAd.destroy();
            this._interstitialAd.offLoad(() => { });
            this._interstitialAd.offClose(() => { });
            this._interstitialAd.onError(() => { });
            this._interstitialAd = null;
            callback(true);
        })

        this._interstitialAd.onError((err) => {
            printLog('插屏广告异常3:', err.msg);
            this._interstitialAd.destroy();
            this._interstitialAd.offLoad(() => { });
            this._interstitialAd.offClose(() => { });
            this._interstitialAd.onError(() => { });
            this._interstitialAd = null;
            callback(true);
        });
    }

    // 主动分享
    shareAppMessage() {
        return new Promise<any>((resolve, reject) => {
            resolve({
                status: true,
                msg: '分享成功'
            })
        })
    }
}
